package com.ylb.rent.util;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.ijpay.alipay.AliPayApi;
import com.ylb.rent.config.AliPayConfigBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/7/5 14:58
 */
@Component
@Slf4j
public class AliPayUtil {

    private static final String SUBJECT="北美留学生租房网";
    private static final String BODY="PC 北美留学生租房网测试";

    @Autowired
    AliPayConfigBean aliPayConfigBean;


    public void pcPay(String uuid,String total,HttpServletResponse response) {
        try {

            String returnUrl = aliPayConfigBean.getDomain() + aliPayConfigBean.getReturnUrl();
            String notifyUrl = aliPayConfigBean.getDomain() + aliPayConfigBean.getNotifyUrl();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            model.setOutTradeNo(uuid);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount(total);
            model.setSubject(SUBJECT);
            model.setBody(BODY);
            model.setPassbackParams("passback_params");

            AliPayApi.tradePage(response, model, notifyUrl, returnUrl);
            // https://opensupport.alipay.com/support/helpcenter/192/201602488772?ant_source=antsupport
            // Alipay Easy SDK（新版）目前只支持输出form表单，不支持打印出url链接。
            // AliPayApi.tradePage(response, "GET", model, notifyUrl, returnUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void qrCode(String uuid,String total,HttpServletResponse response){

        String notifyUrl = aliPayConfigBean.getDomain() + aliPayConfigBean.getNotifyUrl();

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

        model.setSubject(SUBJECT);
        model.setTotalAmount(total);
        log.info("[AliPayUtil-qrCode] 获取搭配OrderNo: [{}]",uuid);
        model.setOutTradeNo(uuid);
//        model.setStoreId(uuid);
        model.setTimeoutExpress("5m");

        try {
            String resultStr = AliPayApi.tradePrecreatePayToResponse(model, notifyUrl).getBody();
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            String qrCode = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
            QrCodeUtil.generateQrCode(qrCode,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
